// mock/index.js
import Mock from 'mockjs'
import { getRandomImage } from './common.js'

// ==================== Mock 基础配置 ====================
// 设置 Mock 请求的延迟时间，模拟真实网络请求的延迟
// timeout: '200-600' 表示随机延迟 200-600 毫秒
Mock.setup({
  timeout: '200-600'
})

// ==================== 视频URL列表 ====================
// 可用的视频URL列表，从Google测试视频和示例视频中随机选择
const videoUrls = [
  'https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4',
  'https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4',
  'https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4',
  'https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerEscapes.mp4',
  'https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerFun.mp4',
  'https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerJoyrides.mp4',
  'https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerMeltdowns.mp4',
  'https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/Sintel.mp4',
  'https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/SubaruOutbackOnStreetAndDirt.mp4',
  'https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/TearsOfSteel.mp4',
  // 备用视频源
  'https://sample-videos.com/zip/10mp4/SampleVideo_1280x720_10fps_1mb.mp4',
  'https://sample-videos.com/zip/10mp4/SampleVideo_1280x720_10fps_2mb.mp4',
  'https://sample-videos.com/zip/10mp4/SampleVideo_1280x720_10fps_5mb.mp4'
]

// 获取随机视频URL的函数
const getRandomVideoUrl = () => {
  return videoUrls[Math.floor(Math.random() * videoUrls.length)]
}

// ==================== 数据模板定义 ====================

// 电视剧基础信息模板
const videoTemplate = {
  'id|+1': 1, // 自增ID，从1开始
  title: '@ctitle(5, 15)', // 中文标题，5-15个字符
  description: '@cparagraph(2, 4)', // 中文段落描述，2-4句话
  cover: () => getRandomImage(400, 300, 'drama'), // 封面图片，400x300尺寸
  'totalEpisodes|20-50': 1, // 总集数，随机20-50集
  'currentEpisode|1-10': 1, // 当前更新到第几集，1-10集
  'currentWatchEpisode|1-10': 1, // 用户当前看到了第几集，1-10集
  // 标签数组，从预定义标签中随机选择2-5个
  'tags|2-5': ['@pick(["动作", "冒险", "奇幻", "爱情", "悬疑", "科幻", "历史", "都市", "古装", "武侠"])'],
  // 演员列表，2-6个演员
  'actors|2-6': [
    {
      name: '@cname', // 中文姓名
      role: '@pick(["主角", "配角", "特邀出演"])', // 角色类型
      avatar: () => getRandomImage(50, 50, 'avatar') // 演员头像
    }
  ],
  director: '@cname', // 导演姓名
  producer: '@cname', // 制片人姓名
  releaseDate: '@date("yyyy-MM-dd")', // 上映日期
  'viewCount|100000-9999999': 1, // 观看次数，10万-999万
  'likeCount|10000-999999': 1, // 点赞数，1万-99万
  'favoriteCount|5000-99999': 1, // 收藏数，5千-9万
  'commentCount|100-9999': 1, // 评论数，100-9999
  'followCount|1000-99999': 1, // 追剧人数，1千-9万
  isNew: '@boolean', // 是否新剧，随机布尔值
  isCompleted: '@boolean', // 是否完结
  isPopular: '@boolean', // 是否热门
  isExclusive: '@boolean', // 是否独播
  isFollowing: '@boolean' // 是否正在追剧
}

// 单集视频信息模板
const episodeTemplate = {
  'cid|+1': 101, // 单集ID，从101开始自增
  'episode|+1': 1, // 集数，从1开始自增
  title: '第@increment集 @ctitle(3, 8)', // 单集标题，包含集数和随机标题
  dramaTitle: '@ctitle(5, 15)', // 当前所属电视剧的名称
  description: '@cparagraph(2, 4)', // 当前电视剧的描述
  // 视频时长，从预定义时长中随机选择
  duration: '@pick(["42:30", "45:15", "48:20", "50:45", "38:10"])',
  cover: () => getRandomImage(300, 200, 'drama'), // 单集封面
  'likeCount|500-9999': 1, // 单集点赞数
  'favoriteCount|100-2999': 1, // 单集收藏数
  isLiked: '@boolean', // 是否已点赞
  isFavorited: '@boolean', // 是否已收藏
  'commentCount|50-999': 1, // 单集评论数
  // 评论列表，5-15条评论
  'comments|5-15': [
    {
      'id|+1': 1, // 评论ID
      user: '@cname', // 评论用户
      avatar: () => getRandomImage(50, 50, 'avatar'), // 用户头像
      content: '@cparagraph(1, 2)', // 评论内容，1-2句话
      timestamp: '@date("yyyy-MM-dd")', // 评论时间
      isLiked: '@boolean', // 是否已点赞该评论
      isDisliked: '@boolean', // 是否已踩该评论
      'likeCount|0-999': 1 // 评论点赞数
    }
  ],
  // 视频播放地址将在生成数据后单独赋值
  videoUrl: null
}

// ==================== 电视剧分类定义 ====================
// 预定义的电视剧分类列表，包含分类名称和描述
const dramaCategories = [
  { id: 1, key: 'action', title: '动作剧场', description: '热血沸腾的动作大片' },
  { id: 2, key: 'romance', title: '浪漫情缘', description: '甜蜜温馨的爱情故事' },
  { id: 3, key: 'comedy', title: '欢乐喜剧', description: '轻松幽默的搞笑剧集' },
  { id: 4, key: 'suspense', title: '悬疑推理', description: '烧脑刺激的推理剧' },
  { id: 5, key: 'fantasy', title: '奇幻世界', description: '天马行空的奇幻冒险' },
  { id: 6, key: 'historical', title: '古装传奇', description: '穿越时空的历史大剧' },
  { id: 7, key: 'modern', title: '都市生活', description: '贴近现实的都市剧' },
  { id: 8, key: 'crime', title: '犯罪档案', description: '紧张刺激的犯罪剧' },
  { id: 9, key: 'family', title: '家庭温情', description: '温馨感人的家庭剧' },
  { id: 10, key: 'youth', title: '青春校园', description: '青春洋溢的校园剧' },
  { id: 11, key: 'workplace', title: '职场风云', description: '职场精英的奋斗故事' },
  { id: 12, key: 'military', title: '军旅热血', description: '热血男儿的军旅生涯' },
  { id: 13, key: 'medical', title: '医者仁心', description: '医疗救护的感人故事' },
  { id: 14, key: 'rural', title: '乡村田园', description: '田园牧歌的乡村生活' },
  { id: 15, key: 'business', title: '商战风云', description: '商界大佬的博弈较量' }
]

// 根据分类生成对应标签的电视剧数据
const generateDramaByCategory = (category, count = 10) => {
  const categoryTags = {
    action: ['动作', '冒险', '武侠', '战争'],
    romance: ['爱情', '都市', '偶像'],
    comedy: ['喜剧', '搞笑', '轻松'],
    suspense: ['悬疑', '推理', '犯罪'],
    fantasy: ['奇幻', '玄幻', '仙侠'],
    historical: ['古装', '历史', '宫廷'],
    modern: ['都市', '现代', '时尚'],
    crime: ['犯罪', '悬疑', '刑侦'],
    family: ['家庭', '温情', '亲情'],
    youth: ['青春', '校园', '成长'],
    workplace: ['职场', '商战', '励志'],
    military: ['军旅', '战争', '热血'],
    medical: ['医疗', '救援', '温情'],
    rural: ['乡村', '田园', '生活'],
    business: ['商战', '金融', '都市']
  }

  return Mock.mock({
    [`list|${count}`]: [
      {
        ...videoTemplate,
        // 确保该分类的电视剧包含对应的标签
        tags: categoryTags[category.key] || ['其他'],
        category: category.key
      }
    ]
  }).list
}

// ==================== API 接口模拟 ====================

/**
 * 1. 电视剧列表 API
 * GET /api/dramas?page=1&pageSize=10&category=action&keyword=战争
 * 支持分页、分类筛选、关键词搜索
 */
Mock.mock(/\/api\/dramas(\?.*)?$/, 'get', (options) => {
  // 解析URL参数
  const url = new URL('http://localhost' + options.url)
  const page = parseInt(url.searchParams.get('page')) || 1 // 页码，默认第1页
  const pageSize = parseInt(url.searchParams.get('pageSize')) || 10 // 每页数量，默认10条
  const category = url.searchParams.get('category') // 分类筛选
  const keyword = url.searchParams.get('keyword') // 搜索关键词

  // 生成模拟数据，数量为 pageSize * 10，确保有足够数据进行分页
  const totalData = Mock.mock({
    [`list|${pageSize * 10}`]: [videoTemplate]
  }).list

  // 确保 currentWatchEpisode 不超过 currentEpisode
  totalData.forEach((item) => {
    if (item.currentWatchEpisode > item.currentEpisode) {
      item.currentWatchEpisode = item.currentEpisode
    }
  })

  // 数据筛选逻辑
  let filteredData = totalData

  // 按分类筛选
  if (category && category !== 'all') {
    filteredData = totalData.filter((item) => item.tags.some((tag) => tag.includes(category)))
  }

  // 按关键词搜索（标题和描述）
  if (keyword) {
    filteredData = filteredData.filter((item) => item.title.includes(keyword) || item.description.includes(keyword))
  }

  // 分页处理
  const total = filteredData.length
  const start = (page - 1) * pageSize
  const end = start + pageSize
  const list = filteredData.slice(start, end)

  // 返回标准格式的响应数据
  return {
    code: 200,
    message: 'success',
    data: {
      list, // 当前页数据
      pagination: {
        page, // 当前页码
        pageSize, // 每页数量
        total, // 总记录数
        totalPages: Math.ceil(total / pageSize) // 总页数
      }
    }
  }
})

/**
 * 2. 获取单集详情 API
 * GET /api/dramas/:dramaId/episodes/:episodeId
 * 获取指定电视剧的指定集数详情
 */
Mock.mock(/\/api\/dramas\/(\d+)\/episodes\/(\d+)$/, 'get', (options) => {
  // 从URL中提取参数
  const matches = options.url.match(/\/api\/dramas\/(\d+)\/episodes\/(\d+)$/)
  const dramaId = matches[1] // 电视剧ID
  const episodeId = matches[2] // 集数ID

  // 先生成电视剧基本信息以获取剧名和描述
  const drama = Mock.mock(videoTemplate)
  drama.id = parseInt(dramaId)

  // 生成单集数据，使用传入的ID
  const episode = Mock.mock({
    ...episodeTemplate,
    cid: parseInt(episodeId),
    episode: parseInt(episodeId),
    dramaId: parseInt(dramaId),
    dramaTitle: drama.title, // 使用生成的电视剧名称
    description: drama.description, // 使用生成的电视剧描述
    videoUrl: getRandomVideoUrl() // 确保每次都是随机视频地址
  })

  return {
    code: 200,
    message: 'success',
    data: episode
  }
})

/**
 * 3. 单集视频点赞/取消点赞 API
 * POST /api/episodes/:episodeId/like
 * Body: { action: 'like' | 'unlike' }
 */
Mock.mock(/\/api\/episodes\/(\d+)\/like$/, 'post', (options) => {
  // 提取集数ID
  const episodeId = options.url.match(/\/api\/episodes\/(\d+)\/like$/)[1]
  // 解析请求体
  const body = JSON.parse(options.body)
  const { action } = body // 'like' 表示点赞，'unlike' 表示取消点赞

  return {
    code: 200,
    message: action === 'like' ? '点赞成功' : '取消点赞成功',
    data: {
      episodeId: parseInt(episodeId),
      isLiked: action === 'like', // 当前点赞状态
      likeCount: Mock.Random.integer(1000, 9999) // 更新后的点赞数
    }
  }
})

/**
 * 4. 单集视频收藏/取消收藏 API
 * POST /api/episodes/:episodeId/favorite
 * Body: { action: 'favorite' | 'unfavorite' }
 */
Mock.mock(/\/api\/episodes\/(\d+)\/favorite$/, 'post', (options) => {
  const episodeId = options.url.match(/\/api\/episodes\/(\d+)\/favorite$/)[1]
  const body = JSON.parse(options.body)
  const { action } = body // 'favorite' 表示收藏，'unfavorite' 表示取消收藏

  return {
    code: 200,
    message: action === 'favorite' ? '收藏成功' : '取消收藏成功',
    data: {
      episodeId: parseInt(episodeId),
      isFavorited: action === 'favorite', // 当前收藏状态
      favoriteCount: Mock.Random.integer(100, 999) // 更新后的收藏数
    }
  }
})

/**
 * 5. 电视剧追剧/取消追剧 API
 * POST /api/dramas/:dramaId/follow
 * Body: { action: 'follow' | 'unfollow' }
 */
Mock.mock(/\/api\/dramas\/(\d+)\/follow$/, 'post', (options) => {
  const dramaId = options.url.match(/\/api\/dramas\/(\d+)\/follow$/)[1]
  const body = JSON.parse(options.body)
  const { action } = body // 'follow' 表示追剧，'unfollow' 表示取消追剧

  return {
    code: 200,
    message: action === 'follow' ? '追剧成功' : '取消追剧成功',
    data: {
      dramaId: parseInt(dramaId),
      isFollowing: action === 'follow', // 更新追剧状态字段名
      followCount: Mock.Random.integer(10000, 99999) // 更新后的追剧人数
    }
  }
})

/**
 * 6. 获取电视剧评论列表 API
 * GET /api/dramas/:dramaId/comments?page=1&pageSize=20
 * 获取指定电视剧的评论列表，支持分页
 */
Mock.mock(/\/api\/dramas\/(\d+)\/comments$/, 'get', (options) => {
  // 解析URL参数
  const url = new URL('http://localhost' + options.url)
  const page = parseInt(url.searchParams.get('page')) || 1
  const pageSize = parseInt(url.searchParams.get('pageSize')) || 20

  // 生成评论数据
  const comments = Mock.mock({
    [`list|${pageSize}`]: [
      {
        'id|+1': 1, // 评论ID
        user: '@cname', // 评论用户
        avatar: () => getRandomImage(50, 50, 'avatar'), // 用户头像
        content: '@cparagraph(1, 3)', // 评论内容，1-3句话
        timestamp: '@date("yyyy-MM-dd")', // 评论时间
        isLiked: '@boolean', // 当前用户是否点赞了该评论
        isDisliked: '@boolean', // 当前用户是否踩了该评论
        'likeCount|0-999': 1, // 评论点赞数
        'replyCount|0-50': 1, // 回复数量
        // 评论的回复列表，0-3条回复
        'replies|0-3': [
          {
            'id|+1': 1000, // 回复ID
            user: '@cname', // 回复用户
            avatar: () => getRandomImage(50, 50, 'avatar'), // 回复用户头像
            content: '@csentence(10, 50)', // 回复内容
            timestamp: '@date("yyyy-MM-dd")',
            'likeCount|0-99': 1 // 回复点赞数
          }
        ]
      }
    ]
  })

  return {
    code: 200,
    message: 'success',
    data: {
      dramaId: parseInt(dramaId),
      comments: comments.list,
      pagination: {
        page,
        pageSize,
        total: Mock.Random.integer(100, 9999), // 总评论数
        totalPages: Mock.Random.integer(5, 500) // 总页数
      }
    }
  }
})

/**
 * 添加电视剧评论 API
 * POST /api/dramas/:dramaId/comments
 * Body: { content: '评论内容' }
 */
Mock.mock(/\/api\/dramas\/(\d+)\/comments$/, 'post', (options) => {
  const dramaId = options.url.match(/\/api\/dramas\/(\d+)\/comments$/)[1]
  const body = JSON.parse(options.body)

  // 生成新评论数据
  const newComment = Mock.mock({
    id: '@increment', // 新评论ID
    user: '@cname', // 当前用户（实际项目中从token获取）
    avatar: () => getRandomImage(50, 50, 'avatar'),
    content: body.content, // 用户输入的评论内容
    timestamp: '@date("yyyy-MM-dd")', // 当前时间
    isLiked: false, // 新评论默认未点赞
    isDisliked: false, // 新评论默认未踩
    likeCount: 0, // 新评论点赞数为0
    replyCount: 0, // 新评论回复数为0
    replies: [] // 新评论回复列表为空
  })

  return {
    code: 200,
    message: '评论成功',
    data: newComment
  }
})

/**
 * 7. 获取单集视频评论列表 API
 * GET /api/episodes/:episodeId/comments?page=1&pageSize=20
 */
Mock.mock(/\/api\/episodes\/(\d+)\/comments$/, 'get', (options) => {
  const episodeId = options.url.match(/\/api\/episodes\/(\d+)\/comments$/)[1]

  const url = new URL('http://localhost' + options.url)
  const page = parseInt(url.searchParams.get('page')) || 1
  const pageSize = parseInt(url.searchParams.get('pageSize')) || 20

  // 生成单集评论数据（相比电视剧评论，单集评论通常更简单，不包含回复）
  const comments = Mock.mock({
    [`list|${pageSize}`]: [
      {
        'id|+1': 1,
        user: '@cname',
        avatar: () => getRandomImage(50, 50, 'avatar'),
        content: '@cparagraph(1, 2)', // 单集评论通常较短
        timestamp: '@date("yyyy-MM-dd")',
        isLiked: '@boolean',
        isDisliked: '@boolean',
        'likeCount|0-999': 1,
        'replyCount|0-20': 1 // 单集评论回复较少
      }
    ]
  })

  return {
    code: 200,
    message: 'success',
    data: {
      episodeId: parseInt(episodeId),
      comments: comments.list,
      pagination: {
        page,
        pageSize,
        total: Mock.Random.integer(50, 999), // 单集评论总数通常较少
        totalPages: Mock.Random.integer(3, 50)
      }
    }
  }
})

/**
 * 添加单集视频评论 API
 * POST /api/episodes/:episodeId/comments
 * Body: { content: '评论内容' }
 */
Mock.mock(/\/api\/episodes\/(\d+)\/comments$/, 'post', (options) => {
  const episodeId = options.url.match(/\/api\/episodes\/(\d+)\/comments$/)[1]
  const body = JSON.parse(options.body)

  const newComment = Mock.mock({
    id: '@increment',
    user: '@cname',
    avatar: () => getRandomImage(50, 50, 'avatar'),
    content: body.content,
    timestamp: '@date("yyyy-MM-dd")',
    isLiked: false,
    isDisliked: false,
    likeCount: 0,
    replyCount: 0
  })

  return {
    code: 200,
    message: '评论成功',
    data: newComment
  }
})

/**
 * 获取电视剧详情 API（包含所有集数信息）
 * GET /api/dramas/:dramaId
 * 返回电视剧基本信息和所有集数列表
 * 注意：这个接口需要放在 /api/dramas/:dramaId/episodes 之前，避免路径冲突
 */
Mock.mock(/\/api\/dramas\/(\d+)(?!\/episodes|\/follow|\/comments)(\?.*)?$/, 'get', (options) => {
  console.log('Mock: 获取电视剧详情 API 被调用', options.url)

  const matches = options.url.match(/\/api\/dramas\/(\d+)(?!\/episodes|\/follow|\/comments)/)
  if (!matches) {
    console.error('Mock: URL 匹配失败:', options.url)
    return {
      code: 400,
      message: 'URL格式错误',
      data: null
    }
  }

  const dramaId = matches[1]
  console.log('Mock: 解析到的 dramaId:', dramaId)

  // 生成电视剧基本信息
  const drama = Mock.mock(videoTemplate)
  drama.id = parseInt(dramaId)

  // 确保 currentWatchEpisode 不超过 currentEpisode
  if (drama.currentWatchEpisode > drama.currentEpisode) {
    drama.currentWatchEpisode = drama.currentEpisode
  }

  // 根据总集数生成所有集数的详细信息
  const episodes = []
  for (let i = 1; i <= drama.totalEpisodes; i++) {
    const episode = Mock.mock({
      cid: 100 + i, // 集数ID：101, 102, 103...
      episode: i, // 集数：1, 2, 3...
      title: `第${i}集 ${Mock.Random.ctitle(3, 8)}`, // 集数标题
      dramaTitle: drama.title, // 所属电视剧名称
      description: drama.description, // 所属电视剧描述
      duration: '@pick(["42:30", "45:15", "48:20", "50:45", "38:10"])', // 视频时长
      cover: () => getRandomImage(300, 200, 'drama'), // 单集封面
      'likeCount|500-9999': 1, // 单集点赞数
      'favoriteCount|100-2999': 1, // 单集收藏数
      'viewCount|1000-99999': 1, // 单集观看数
      'commentCount|50-999': 1, // 单集评论数
      isLiked: '@boolean', // 是否已点赞
      isFavorited: '@boolean', // 是否已收藏
      dramaId: parseInt(dramaId), // 添加 dramaId 字段
      // 标记用户是否已观看（基于 currentWatchEpisode）
      isWatched: i <= drama.currentWatchEpisode,
      // 标记是否为当前观看集（用户下次应该看的集数）
      isCurrentWatch: i === drama.currentWatchEpisode + 1 && i <= drama.currentEpisode,
      // 集数状态
      status: i <= drama.currentEpisode ? 'available' : 'coming',
      isVip: Mock.Random.boolean(),
      releaseDate: i <= drama.currentEpisode ? '@date("yyyy-MM-dd")' : '@date("yyyy-MM-dd", "now", "+7d")', // 未更新集数显示未来日期
      // 播放进度（用户观看进度）
      progress: '@integer(0, 100)', // 观看进度百分比
      lastWatchTime: '@date("yyyy-MM-dd")', // 最后观看时间
      // 单集评分
      rating: '@float(7.0, 9.8, 1, 1)', // 单集评分 7.0-9.8
      'ratingCount|100-9999': 1 // 评分人数
    })
    // 为每个集数单独赋值随机视频地址
    episode.videoUrl = getRandomVideoUrl()
    episodes.push(episode)
  }

  // 将集数列表添加到电视剧信息中
  drama.videos = episodes
  drama.episodes = episodes // 添加 episodes 字段确保兼容性

  console.log('Mock: 返回电视剧详情，包含集数:', {
    dramaId: drama.id,
    dramaTitle: drama.title,
    totalEpisodes: drama.totalEpisodes,
    videosCount: episodes.length,
    episodesCount: episodes.length,
    hasVideos: !!drama.videos,
    hasEpisodes: !!drama.episodes,
    videosLength: drama.videos?.length || 0,
    episodesLength: drama.episodes?.length || 0
  })

  const result = {
    code: 200,
    message: 'success',
    data: drama
  }

  console.log('Mock: 最终返回的数据结构:', {
    hasData: !!result.data,
    hasVideos: !!result.data.videos,
    hasEpisodes: !!result.data.episodes,
    videosCount: result.data.videos?.length || 0,
    episodesCount: result.data.episodes?.length || 0
  })

  return result
})

/**
 * 获取用户追剧列表 API
 * GET /api/dramas/following?page=1&pageSize=10
 * 获取当前用户正在追的所有电视剧
 */
Mock.mock(/\/api\/dramas\/following(\?.*)?$/, 'get', (options) => {
  console.log('获取用户追剧列表 API 被调用', options)
  // 解析URL参数
  const url = new URL('http://localhost' + options.url)
  const page = parseInt(url.searchParams.get('page')) || 1
  const pageSize = parseInt(url.searchParams.get('pageSize')) || 10

  // 生成追剧数据，确保 isFollowing 为 true
  const followingData = Mock.mock({
    [`list|${pageSize * 3}`]: [
      {
        ...videoTemplate,
        isFollowing: true, // 追剧列表中所有电视剧都是正在追的
        followDate: '@date("yyyy-MM-dd")', // 追剧开始时间
        lastWatchEpisode: '@integer(1, 10)', // 最后观看到第几集（保持兼容性）
        currentWatchEpisode: '@integer(1, 10)', // 用户当前看到了第几集（新字段）
        lastWatchTime: '@date("yyyy-MM-dd")', // 最后观看时间
        hasUpdate: '@boolean', // 是否有更新
        updateEpisodeCount: '@integer(0, 3)' // 新更新集数
      }
    ]
  }).list

  // 确保 currentWatchEpisode 不超过 currentEpisode（已更新的集数）
  followingData.forEach((item) => {
    if (item.currentWatchEpisode > item.currentEpisode) {
      item.currentWatchEpisode = item.currentEpisode
    }
    // 同步 lastWatchEpisode 字段保持一致性
    item.lastWatchEpisode = item.currentWatchEpisode
  })

  // 分页处理
  const total = followingData.length
  const start = (page - 1) * pageSize
  const end = start + pageSize
  const list = followingData.slice(start, end)

  return {
    code: 200,
    message: 'success',
    data: {
      list, // 当前页追剧列表
      pagination: {
        page,
        pageSize,
        total,
        totalPages: Math.ceil(total / pageSize)
      },
      statistics: {
        totalFollowing: total, // 总追剧数
        hasUpdateCount: list.filter((item) => item.hasUpdate).length, // 有更新的剧集数
        completedCount: list.filter((item) => item.isCompleted).length // 已完结的剧集数
      }
    }
  }
})

/**
 * 获取电视剧所有集数列表 API
 * GET /api/dramas/:dramaId/episodes?page=1&pageSize=20&sort=asc
 * 获取指定电视剧的所有集数列表，支持分页和排序
 *
 * 查询参数：
 * - page: 页码，默认1
 * - pageSize: 每页数量，默认20
 * - sort: 排序方式，asc(正序)/desc(倒序)，默认asc
 * - status: 筛选状态，all(全部)/available(可观看)/coming(即将上线)，默认all
 */
Mock.mock(/\/api\/dramas\/(\d+)\/episodes(\?.*)?$/, 'get', (options) => {
  const dramaId = options.url.match(/\/api\/dramas\/(\d+)\/episodes/)[1]

  // 解析URL参数
  const url = new URL('http://localhost' + options.url)
  const page = parseInt(url.searchParams.get('page')) || 1
  const pageSize = parseInt(url.searchParams.get('pageSize')) || 20
  const sort = url.searchParams.get('sort') || 'asc' // asc: 正序, desc: 倒序
  const status = url.searchParams.get('status') || 'all' // all: 全部, available: 可观看, coming: 即将上线

  // 先获取电视剧基本信息
  const drama = Mock.mock({
    ...videoTemplate,
    id: parseInt(dramaId)
  })

  // 确保 currentWatchEpisode 不超过 currentEpisode
  if (drama.currentWatchEpisode > drama.currentEpisode) {
    drama.currentWatchEpisode = drama.currentEpisode
  }

  // 生成所有集数数据
  const allEpisodes = []
  for (let i = 1; i <= drama.totalEpisodes; i++) {
    const episode = Mock.mock({
      cid: 100 + i, // 集数ID：101, 102, 103...
      episode: i, // 集数：1, 2, 3...
      title: `第${i}集 ${Mock.Random.ctitle(3, 8)}`, // 集数标题
      dramaTitle: drama.title, // 所属电视剧名称
      description: drama.description, // 所属电视剧描述
      duration: '@pick(["42:30", "45:15", "48:20", "50:45", "38:10"])', // 视频时长
      cover: () => getRandomImage(300, 200, 'drama'), // 单集封面
      'likeCount|500-9999': 1, // 单集点赞数
      'favoriteCount|100-2999': 1, // 单集收藏数
      'viewCount|1000-99999': 1, // 单集观看数
      'commentCount|50-999': 1, // 单集评论数
      isLiked: '@boolean', // 是否已点赞
      isFavorited: '@boolean', // 是否已收藏
      // 集数状态：available(可观看), coming(即将上线), vip(VIP专享)
      'status|1': i <= drama.currentEpisode ? ['available'] : ['coming'],
      isVip: '@boolean', // 是否需要VIP
      releaseDate: i <= drama.currentEpisode ? '@date("yyyy-MM-dd")' : '@date("yyyy-MM-dd", "now", "+7d")', // 未更新集数显示未来日期
      dramaId: parseInt(dramaId), // 所属电视剧ID
      // 播放进度（用户观看进度）
      progress: '@integer(0, 100)', // 观看进度百分比
      lastWatchTime: '@date("yyyy-MM-dd")', // 最后观看时间
      // 单集评分
      rating: '@float(7.0, 9.8, 1, 1)', // 单集评分 7.0-9.8
      'ratingCount|100-9999': 1, // 评分人数
      // 基于用户观看进度的状态标记
      isWatched: i <= drama.currentWatchEpisode, // 是否已观看
      isCurrentWatch: i === drama.currentWatchEpisode + 1 && i <= drama.currentEpisode // 是否为当前应观看集数
    })
    // 为每个集数单独赋值随机视频地址
    episode.videoUrl = i <= drama.currentEpisode ? getRandomVideoUrl() : null
    allEpisodes.push(episode)
  }

  // 状态筛选
  let filteredEpisodes = allEpisodes
  if (status !== 'all') {
    filteredEpisodes = allEpisodes.filter((episode) => {
      if (status === 'available') {
        return episode.status === 'available'
      } else if (status === 'coming') {
        return episode.status === 'coming'
      }
      return true
    })
  }

  // 排序处理
  if (sort === 'desc') {
    filteredEpisodes.reverse() // 倒序：最新集数在前
  }
  // 默认正序：第1集在前

  // 分页处理
  const total = filteredEpisodes.length
  const start = (page - 1) * pageSize
  const end = start + pageSize
  const list = filteredEpisodes.slice(start, end)

  return {
    code: 200,
    message: 'success',
    data: {
      dramaId: parseInt(dramaId),
      dramaInfo: {
        id: drama.id,
        title: drama.title,
        cover: drama.cover,
        totalEpisodes: drama.totalEpisodes,
        currentEpisode: drama.currentEpisode,
        currentWatchEpisode: drama.currentWatchEpisode, // 添加用户当前观看进度
        isCompleted: drama.isCompleted,
        isFollowing: drama.isFollowing, // 添加追剧状态
        tags: drama.tags,
        description: drama.description
      },
      episodes: list, // 当前页集数列表
      pagination: {
        page, // 当前页码
        pageSize, // 每页数量
        total, // 总集数
        totalPages: Math.ceil(total / pageSize), // 总页数
        availableCount: allEpisodes.filter((ep) => ep.status === 'available').length, // 可观看集数
        comingCount: allEpisodes.filter((ep) => ep.status === 'coming').length, // 即将上线集数
        watchedCount: allEpisodes.filter((ep) => ep.isWatched).length, // 已观看集数
        unwatchedCount: allEpisodes.filter((ep) => ep.status === 'available' && !ep.isWatched).length // 可观看但未观看集数
      },
      sort, // 当前排序方式
      status // 当前筛选状态
    }
  }
})

/**
 * 获取电视剧所有集数列表 API（不分页）
 * GET /api/dramas/:dramaId/episodes/all?sort=asc&status=all
 * 一次性返回指定电视剧的所有集数，支持排序和状态筛选
 *
 * 查询参数：
 * - sort: 排序方式，asc(正序)/desc(倒序)，默认asc
 * - status: 筛选状态，all(全部)/available(可观看)/coming(即将上线)，默认all
 */
Mock.mock(/\/api\/dramas\/(\d+)\/episodes\/all(\?.*)?$/, 'get', (options) => {
  console.log('Mock API 接收到请求:', options.url)

  const matches = options.url.match(/\/api\/dramas\/(\d+)\/episodes\/all/)
  if (!matches) {
    console.error('URL 匹配失败:', options.url)
    return {
      code: 400,
      message: 'URL格式错误',
      data: null
    }
  }

  const dramaId = matches[1]

  // 更安全的URL参数解析
  let sort = 'asc'
  let status = 'all'

  try {
    // 尝试解析查询参数
    if (options.url.includes('?')) {
      const queryString = options.url.split('?')[1]
      const params = new URLSearchParams(queryString)
      sort = params.get('sort') || 'asc'
      status = params.get('status') || 'all'
    }
  } catch (error) {
    console.warn('URL参数解析失败，使用默认值:', error)
  }

  console.log('获取电视剧所有集数 API 被调用', { dramaId, sort, status, url: options.url })

  // 先获取电视剧基本信息
  const drama = Mock.mock({
    ...videoTemplate,
    id: parseInt(dramaId)
  })

  // 确保 currentWatchEpisode 不超过 currentEpisode
  if (drama.currentWatchEpisode > drama.currentEpisode) {
    drama.currentWatchEpisode = drama.currentEpisode
  }

  // 生成所有集数数据
  const allEpisodes = []
  for (let i = 1; i <= drama.totalEpisodes; i++) {
    const episode = Mock.mock({
      cid: 100 + i, // 集数ID：101, 102, 103...
      episode: i, // 集数：1, 2, 3...
      title: `第${i}集 ${Mock.Random.ctitle(3, 8)}`, // 集数标题
      dramaTitle: drama.title, // 所属电视剧名称
      description: drama.description, // 所属电视剧描述
      duration: '@pick(["42:30", "45:15", "48:20", "50:45", "38:10"])', // 视频时长
      cover: () => getRandomImage(300, 200, 'drama'), // 单集封面
      'likeCount|500-9999': 1, // 单集点赞数
      'favoriteCount|100-2999': 1, // 单集收藏数
      'viewCount|1000-99999': 1, // 单集观看数
      'commentCount|50-999': 1, // 单集评论数
      isLiked: '@boolean', // 是否已点赞
      isFavorited: '@boolean', // 是否已收藏
      // 集数状态：available(可观看), coming(即将上线), vip(VIP专享)
      'status|1': i <= drama.currentEpisode ? ['available'] : ['coming'],
      isVip: '@boolean', // 是否需要VIP
      releaseDate: i <= drama.currentEpisode ? '@date("yyyy-MM-dd")' : '@date("yyyy-MM-dd", "now", "+7d")', // 未更新集数显示未来日期
      dramaId: parseInt(dramaId), // 所属电视剧ID
      // 播放进度（用户观看进度）
      progress: '@integer(0, 100)', // 观看进度百分比
      lastWatchTime: '@date("yyyy-MM-dd")', // 最后观看时间
      // 单集评分
      rating: '@float(7.0, 9.8, 1, 1)', // 单集评分 7.0-9.8
      'ratingCount|100-9999': 1, // 评分人数
      // 基于用户观看进度的状态标记
      isWatched: i <= drama.currentWatchEpisode, // 是否已观看
      isCurrentWatch: i === drama.currentWatchEpisode + 1 && i <= drama.currentEpisode // 是否为当前应观看集数
    })
    // 为每个集数单独赋值随机视频地址
    episode.videoUrl = i <= drama.currentEpisode ? getRandomVideoUrl() : null
    allEpisodes.push(episode)
  }

  // 状态筛选
  let filteredEpisodes = allEpisodes
  if (status !== 'all') {
    filteredEpisodes = allEpisodes.filter((episode) => {
      if (status === 'available') {
        return episode.status === 'available'
      } else if (status === 'coming') {
        return episode.status === 'coming'
      }
      return true
    })
  }

  // 排序处理
  if (sort === 'desc') {
    filteredEpisodes.reverse() // 倒序：最新集数在前
  }
  // 默认正序：第1集在前

  const result = {
    code: 200,
    message: 'success',
    data: {
      dramaId: parseInt(dramaId),
      dramaInfo: {
        id: drama.id,
        title: drama.title,
        cover: drama.cover,
        totalEpisodes: drama.totalEpisodes,
        currentEpisode: drama.currentEpisode,
        currentWatchEpisode: drama.currentWatchEpisode, // 添加用户当前观看进度
        isCompleted: drama.isCompleted,
        isFollowing: drama.isFollowing, // 添加追剧状态
        tags: drama.tags,
        description: drama.description
      },
      episodes: filteredEpisodes, // 所有集数列表（根据筛选条件）
      statistics: {
        total: filteredEpisodes.length, // 修复：使用正确的总数
        availableCount: allEpisodes.filter((ep) => ep.status === 'available').length, // 可观看集数
        comingCount: allEpisodes.filter((ep) => ep.status === 'coming').length, // 即将上线集数
        watchedCount: allEpisodes.filter((ep) => ep.isWatched).length, // 已观看集数
        unwatchedCount: allEpisodes.filter((ep) => ep.status === 'available' && !ep.isWatched).length // 可观看但未观看集数
      },
      sort, // 当前排序方式
      status // 当前筛选状态
    }
  }

  console.log('Mock API 返回数据:', {
    dramaId: result.data.dramaId,
    episodeCount: result.data.episodes.length,
    totalEpisodes: result.data.dramaInfo.totalEpisodes
  })

  return result
})

/**
 * 获取分类电视剧集合 API
 * GET /api/dramas/categories?page=1&pageSize=10&dramaCount=10
 * 返回按分类组织的电视剧集合，每个分类包含指定数量的电视剧
 */
Mock.mock(/\/api\/dramas\/categories(\?.*)?$/, 'get', (options) => {
  console.log('获取分类电视剧集合 API 被调用', options)

  // 解析URL参数
  const url = new URL('http://localhost' + options.url)
  const page = parseInt(url.searchParams.get('page')) || 1
  const pageSize = parseInt(url.searchParams.get('pageSize')) || 10
  const dramaCount = parseInt(url.searchParams.get('dramaCount')) || 10

  // 分页获取分类
  const totalCategories = dramaCategories.length
  const start = (page - 1) * pageSize
  const end = start + pageSize
  const currentCategories = dramaCategories.slice(start, end)

  // 为每个分类生成电视剧数据
  const categoriesWithDramas = currentCategories.map((category) => {
    const dramas = generateDramaByCategory(category, dramaCount)

    return {
      categoryId: category.id,
      categoryKey: category.key,
      categoryTitle: category.title,
      categoryDescription: category.description,
      totalCount: Mock.Random.integer(50, 200), // 该分类总电视剧数量
      dramas: dramas,
      // 分类统计信息
      stats: {
        newCount: dramas.filter((drama) => drama.isNew).length,
        popularCount: dramas.filter((drama) => drama.isPopular).length,
        completedCount: dramas.filter((drama) => drama.isCompleted).length,
        exclusiveCount: dramas.filter((drama) => drama.isExclusive).length
      }
    }
  })

  return {
    code: 200,
    message: 'success',
    data: {
      categories: categoriesWithDramas, // 分类电视剧集合
      pagination: {
        page,
        pageSize,
        total: totalCategories, // 总分类数
        totalPages: Math.ceil(totalCategories / pageSize), // 总页数
        hasMore: end < totalCategories // 是否还有更多分类
      },
      summary: {
        totalCategories, // 总分类数
        currentCategoriesCount: currentCategories.length, // 当前页分类数
        dramaCountPerCategory: dramaCount, // 每个分类电视剧数量
        totalDramasReturned: currentCategories.length * dramaCount // 本次返回的总电视剧数
      }
    }
  }
})

// 生成精选单集视频数据
const generateFeaturedEpisode = () => {
  // 随机选择一个分类来生成对应的电视剧
  const randomCategory = dramaCategories[Math.floor(Math.random() * dramaCategories.length)]
  const dramas = generateDramaByCategory(randomCategory, 1)
  const drama = dramas[0] // 确保获取到第一个电视剧

  // 确保drama存在，如果不存在则创建一个默认的
  const safeDrama =
    drama ||
    Mock.mock({
      ...videoTemplate,
      id: Mock.Random.integer(1000, 9999),
      category: randomCategory.key,
      tags: ['动作', '冒险'] // 默认标签
    })

  const episode = Mock.mock({
    'cid|+1': 2001, // 精选视频ID，从2001开始
    'episode|1-50': 1, // 集数，1-50集
    title: `第@integer(1, 50)集 @ctitle(3, 8)`, // 单集标题
    dramaTitle: safeDrama.title, // 所属电视剧名称
    description: safeDrama.description, // 所属电视剧描述
    duration: '@pick(["42:30", "45:15", "48:20", "50:45", "38:10", "52:20", "47:35"])', // 视频时长
    cover: () => getRandomImage(400, 225, 'episode'), // 16:9比例的单集封面

    // 高数值的互动数据（精选视频特征）
    'likeCount|50000-500000': 1, // 高点赞数：5万-50万
    'favoriteCount|20000-200000': 1, // 高收藏数：2万-20万
    'commentCount|5000-50000': 1, // 高评论数：5千-5万
    'viewCount|500000-5000000': 1, // 高观看数：50万-500万
    'shareCount|1000-50000': 1, // 分享数：1千-5万

    // 用户交互状态
    isLiked: '@boolean',
    isFavorited: '@boolean',
    isShared: '@boolean',

    // 质量指标
    'rating|8.5-9.8': 1, // 高评分：8.5-9.8
    'ratingCount|10000-100000': 1, // 评分人数：1万-10万

    // 所属电视剧信息
    drama: {
      id: safeDrama.id,
      title: safeDrama.title,
      cover: safeDrama.cover,
      tags: safeDrama.tags,
      category: safeDrama.category,
      isNew: safeDrama.isNew,
      isPopular: safeDrama.isPopular,
      isExclusive: safeDrama.isExclusive,
      director: safeDrama.director,
      actors: safeDrama.actors
    },

    // 精选相关信息
    featuredReason: '@pick(["热门推荐", "编辑精选", "用户最爱", "口碑之选", "新剧力推", "经典回顾"])', // 精选理由
    featuredDate: '@date("yyyy-MM-dd")', // 入选精选时间
    'hotScore|85-100': 1, // 热度评分：85-100

    // 标签和分类
    episodeTags:
      '@pick([["精彩", "高能", "催泪"], ["搞笑", "轻松", "治愈"], ["悬疑", "烧脑", "反转"], ["动作", "刺激", "爆燃"]])', // 单集标签

    // 时间信息
    releaseDate: '@date("yyyy-MM-dd")', // 播出日期
    addToFeaturedTime: '@date("yyyy-MM-dd")', // 加入精选时间

    // 综合排序分数（用于排序算法）
    'comprehensiveScore|90-100': 1, // 综合评分

    // 播放相关
    'progress|0-100': 1, // 用户观看进度
    lastWatchTime: '@date("yyyy-MM-dd")', // 最后观看时间

    // 推荐相关
    'recommendScore|80-100': 1, // 推荐度评分
    'freshness|70-100': 1 // 新鲜度（最近热度）
  })

  // 为每个精选视频单独赋值随机视频地址
  episode.videoUrl = getRandomVideoUrl()

  return episode
}

/**
 * 获取精选视频列表 API
 * GET /api/episodes/featured?page=1&pageSize=15&sortBy=comprehensive&timeRange=all
 * 返回收藏、点赞、评论最多的精选单集视频列表
 */
Mock.mock(/\/api\/episodes\/featured(\?.*)?$/, 'get', (options) => {
  console.log('获取精选视频列表 API 被调用', options)

  // 解析URL参数
  const url = new URL('http://localhost' + options.url)
  const page = parseInt(url.searchParams.get('page')) || 1
  const pageSize = parseInt(url.searchParams.get('pageSize')) || 15
  const sortBy = url.searchParams.get('sortBy') || 'comprehensive'
  const timeRange = url.searchParams.get('timeRange') || 'all'

  // 生成大量精选视频数据用于分页
  const totalFeaturedData = []
  for (let i = 0; i < pageSize * 10; i++) {
    totalFeaturedData.push(generateFeaturedEpisode())
  }

  // 根据排序方式排序
  let sortedData = [...totalFeaturedData]
  switch (sortBy) {
    case 'like':
      sortedData.sort((a, b) => b.likeCount - a.likeCount)
      break
    case 'favorite':
      sortedData.sort((a, b) => b.favoriteCount - a.favoriteCount)
      break
    case 'comment':
      sortedData.sort((a, b) => b.commentCount - a.commentCount)
      break
    case 'comprehensive':
    default:
      sortedData.sort((a, b) => b.comprehensiveScore - a.comprehensiveScore)
      break
  }

  // 根据时间范围筛选（模拟）
  let filteredData = sortedData
  if (timeRange === 'week') {
    // 模拟一周内的数据（实际项目中会根据时间字段筛选）
    filteredData = sortedData.filter(() => Math.random() > 0.3)
  } else if (timeRange === 'month') {
    // 模拟一个月内的数据
    filteredData = sortedData.filter(() => Math.random() > 0.1)
  }

  // 分页处理
  const total = filteredData.length
  const start = (page - 1) * pageSize
  const end = start + pageSize
  const list = filteredData.slice(start, end)

  // 为每个视频添加排名信息
  const rankedList = list.map((item, index) => ({
    ...item,
    rank: start + index + 1, // 排名
    isTopRank: start + index < 3, // 是否前三名
    rankChange: Mock.Random.pick(['up', 'down', 'same', 'new']), // 排名变化
    'rankChangeValue|1-10': 1 // 排名变化数值
  }))

  return {
    code: 200,
    message: 'success',
    data: {
      episodes: rankedList, // 精选视频列表
      pagination: {
        page,
        pageSize,
        total,
        totalPages: Math.ceil(total / pageSize),
        hasMore: end < total
      },
      filters: {
        sortBy, // 当前排序方式
        timeRange, // 当前时间范围
        availableSorts: [
          { key: 'comprehensive', label: '综合排序' },
          { key: 'like', label: '点赞最多' },
          { key: 'favorite', label: '收藏最多' },
          { key: 'comment', label: '评论最多' }
        ],
        availableTimeRanges: [
          { key: 'all', label: '全部时间' },
          { key: 'week', label: '一周内' },
          { key: 'month', label: '一个月内' }
        ]
      },
      statistics: {
        totalFeaturedEpisodes: total, // 总精选视频数
        averageLikeCount: Math.floor(rankedList.reduce((sum, item) => sum + item.likeCount, 0) / rankedList.length), // 平均点赞数
        averageFavoriteCount: Math.floor(
          rankedList.reduce((sum, item) => sum + item.favoriteCount, 0) / rankedList.length
        ), // 平均收藏数
        averageCommentCount: Math.floor(
          rankedList.reduce((sum, item) => sum + item.commentCount, 0) / rankedList.length
        ), // 平均评论数
        topRatingEpisode: rankedList.reduce((max, item) => (item.rating > max.rating ? item : max), rankedList[0]), // 评分最高的视频
        hotCategories: [
          // 热门分类统计
          { category: '动作剧场', count: Mock.Random.integer(20, 50) },
          { category: '浪漫情缘', count: Mock.Random.integer(15, 40) },
          { category: '悬疑推理', count: Mock.Random.integer(10, 35) },
          { category: '欢乐喜剧', count: Mock.Random.integer(8, 30) },
          { category: '奇幻世界', count: Mock.Random.integer(5, 25) }
        ]
      },
      lastUpdateTime: '@date("yyyy-MM-dd")', // 精选列表最后更新时间
      nextUpdateTime: '@date("yyyy-MM-dd", "now", "+1d")' // 下次更新时间
    }
  }
})

console.log('Mock API 已启动 - 所有接口已注册完成')

// ==================== 追剧相关Mock API ====================

/**
 * 追剧/取消追剧操作 API
 * POST /api/dramas/:dramaId/follow
 * Body: { action: 'follow' | 'unfollow' }
 */
Mock.mock(/\/api\/dramas\/(\d+)\/follow$/, 'post', (options) => {
  const dramaId = options.url.match(/\/api\/dramas\/(\d+)\/follow$/)[1]
  const body = JSON.parse(options.body)
  const { action } = body

  return {
    code: 200,
    message: action === 'follow' ? '追剧成功' : '取消追剧成功',
    data: {
      dramaId: parseInt(dramaId),
      isFollowing: action === 'follow',
      followCount: Mock.Random.integer(10000, 99999),
      followTime: action === 'follow' ? '@date("yyyy-MM-dd")' : null
    }
  }
})

/**
 * 获取我的追剧列表 API
 * GET /api/user/following?page=1&pageSize=10&sort=follow_time&status=all
 */
Mock.mock(/\/api\/user\/following(\?.*)?$/, 'get', (options) => {
  const url = new URL('http://localhost' + options.url)
  const page = parseInt(url.searchParams.get('page')) || 1
  const pageSize = parseInt(url.searchParams.get('pageSize')) || 10
  const sort = url.searchParams.get('sort') || 'follow_time'
  const status = url.searchParams.get('status') || 'all'

  // 生成追剧列表数据
  const followingList = Mock.mock({
    [`list|${pageSize * 3}`]: [
      {
        ...videoTemplate,
        isFollowing: true,
        followTime: '@date("yyyy-MM-dd")',
        lastWatchEpisode: '@integer(1, 10)',
        currentWatchEpisode: '@integer(1, 10)', // 添加当前观看进度字段
        lastWatchTime: '@date("yyyy-MM-dd")',
        hasUpdate: '@boolean',
        updateEpisodeCount: '@integer(0, 5)',
        watchProgress: '@float(0, 1, 2, 2)'
      }
    ]
  }).list

  // 确保观看进度的合理性
  followingList.forEach((item) => {
    if (item.currentWatchEpisode > item.currentEpisode) {
      item.currentWatchEpisode = item.currentEpisode
    }
    // 保持字段一致性
    item.lastWatchEpisode = item.currentWatchEpisode
  })

  // 状态筛选
  let filteredList = followingList
  if (status === 'updating') {
    filteredList = followingList.filter((item) => !item.isCompleted)
  } else if (status === 'completed') {
    filteredList = followingList.filter((item) => item.isCompleted)
  } else if (status === 'has_update') {
    filteredList = followingList.filter((item) => item.hasUpdate)
  }

  // 排序
  if (sort === 'update_time') {
    filteredList.sort((a, b) => new Date(b.lastWatchTime) - new Date(a.lastWatchTime))
  } else if (sort === 'watch_progress') {
    filteredList.sort((a, b) => b.watchProgress - a.watchProgress)
  } else {
    filteredList.sort((a, b) => new Date(b.followTime) - new Date(a.followTime))
  }

  // 分页
  const total = filteredList.length
  const start = (page - 1) * pageSize
  const end = start + pageSize
  const list = filteredList.slice(start, end)

  return {
    code: 200,
    message: 'success',
    data: {
      list,
      pagination: {
        page,
        pageSize,
        total,
        totalPages: Math.ceil(total / pageSize)
      },
      statistics: {
        totalFollowing: total,
        hasUpdateCount: filteredList.filter((item) => item.hasUpdate).length,
        completedCount: filteredList.filter((item) => item.isCompleted).length,
        updatingCount: filteredList.filter((item) => !item.isCompleted).length
      }
    }
  }
})

// ==================== 浏览记录相关Mock API ====================

/**
 * 记录视频浏览 API
 * POST /api/user/browsing-history
 * Body: { dramaId, episodeId, watchProgress?, watchPosition? }
 */
Mock.mock(/\/api\/user\/browsing-history$/, 'post', (options) => {
  const body = JSON.parse(options.body)
  const { dramaId, episodeId, watchProgress = 0, watchPosition = '00:00' } = body

  // 生成浏览记录
  const browsingRecord = Mock.mock({
    id: '@increment',
    dramaId: parseInt(dramaId),
    episodeId: parseInt(episodeId),
    dramaTitle: '@ctitle(5, 15)',
    episodeTitle: `第${episodeId}集 @ctitle(3, 8)`,
    cover: () => getRandomImage(300, 200, 'episode'),
    duration: '@pick(["42:30", "45:15", "48:20", "50:45", "38:10"])',
    watchTime: '@date("yyyy-MM-dd")',
    watchProgress: watchProgress,
    lastWatchPosition: watchPosition,
    deviceType: '@pick(["mobile", "desktop", "tablet"])',
    'watchDuration|300-2700': 1 // 观看时长(秒)
  })

  return {
    code: 200,
    message: '浏览记录已保存',
    data: browsingRecord
  }
})

/**
 * 获取浏览记录列表 API
 * GET /api/user/browsing-history?page=1&pageSize=20&sort=watch_time&timeRange=all&dramaId=
 */
Mock.mock(/\/api\/user\/browsing-history(\?.*)?$/, 'get', (options) => {
  const url = new URL('http://localhost' + options.url)
  const page = parseInt(url.searchParams.get('page')) || 1
  const pageSize = parseInt(url.searchParams.get('pageSize')) || 20
  const sort = url.searchParams.get('sort') || 'watch_time'
  const timeRange = url.searchParams.get('timeRange') || 'all'
  const dramaId = url.searchParams.get('dramaId')

  // 生成浏览记录数据 - 使用与追剧列表相同的电视剧数据结构
  const historyList = Mock.mock({
    [`list|${pageSize * 5}`]: [
      {
        ...videoTemplate, // 使用完整的电视剧数据模板
        // 浏览记录特有字段
        'id|+1': 1001, // 浏览记录ID
        watchTime: '@date("yyyy-MM-dd")', // 最后观看时间
        'watchProgress|0-1': 1, // 观看进度百分比
        lastWatchPosition: '@pick(["05:30", "12:45", "25:10", "38:20", "41:50"])', // 最后观看位置
        deviceType: '@pick(["mobile", "desktop", "tablet"])', // 观看设备类型
        'watchDuration|300-2700': 1, // 观看时长(秒)

        // 当前观看的具体集数信息
        'currentWatchEpisodeId|101-150': 1, // 当前观看集数的ID
        currentWatchEpisodeTitle: '第@integer(1, 30)集 @ctitle(3, 8)', // 当前观看集数标题

        // 追剧状态（浏览记录中可能包含未追剧的内容）
        isStarred: '@boolean', // 是否已追剧（用于浏览记录中的追剧按钮）
        isFollowing: '@boolean', // 是否正在追剧

        // 浏览相关统计
        'browseCount|1-50': 1, // 浏览次数
        firstWatchTime: '@date("yyyy-MM-dd")', // 首次观看时间

        // 最近更新信息
        hasUpdate: '@boolean', // 是否有更新
        'updateEpisodeCount|0-5': 1, // 新更新集数
        lastUpdateTime: '@date("yyyy-MM-dd")' // 最后更新时间
      }
    ]
  }).list

  // 按电视剧ID筛选
  let filteredList = historyList
  if (dramaId) {
    filteredList = historyList.filter((item) => item.id === parseInt(dramaId))
  }

  // 时间范围筛选（模拟）
  if (timeRange === 'today') {
    filteredList = filteredList.filter(() => Math.random() > 0.7)
  } else if (timeRange === 'week') {
    filteredList = filteredList.filter(() => Math.random() > 0.3)
  } else if (timeRange === 'month') {
    filteredList = filteredList.filter(() => Math.random() > 0.1)
  }

  // 排序
  if (sort === 'drama_title') {
    filteredList.sort((a, b) => a.title.localeCompare(b.title))
  } else {
    filteredList.sort((a, b) => new Date(b.watchTime) - new Date(a.watchTime))
  }

  // 分页
  const total = filteredList.length
  const start = (page - 1) * pageSize
  const end = start + pageSize
  const list = filteredList.slice(start, end)

  return {
    code: 200,
    message: 'success',
    data: {
      list,
      pagination: {
        page,
        pageSize,
        total,
        totalPages: Math.ceil(total / pageSize)
      },
      statistics: {
        totalRecords: total,
        todayCount: Math.floor(total * 0.1),
        weekCount: Math.floor(total * 0.3),
        monthCount: Math.floor(total * 0.6),
        uniqueDramas: new Set(list.map((item) => item.id)).size, // 使用电视剧ID统计
        followingCount: list.filter((item) => item.isFollowing).length, // 正在追剧的数量
        unfinishedCount: list.filter((item) => !item.isCompleted).length, // 未完结的数量
        avgWatchProgress: (list.reduce((sum, item) => sum + item.watchProgress, 0) / list.length).toFixed(2),
        totalWatchTime: list.reduce((sum, item) => sum + item.watchDuration, 0), // 总观看时长
        recentlyUpdatedCount: list.filter((item) => item.hasUpdate).length // 最近有更新的数量
      }
    }
  }
})

// ==================== 用户点赞相关Mock API ====================

/**
 * 获取用户点赞的电视剧列表 API
 * GET /api/user/liked-dramas?page=1&pageSize=10&sort=like_time&likeType=all
 */
Mock.mock(/\/api\/user\/liked-dramas(\?.*)?$/, 'get', (options) => {
  const url = new URL('http://localhost' + options.url)
  const page = parseInt(url.searchParams.get('page')) || 1
  const pageSize = parseInt(url.searchParams.get('pageSize')) || 10
  const sort = url.searchParams.get('sort') || 'like_time'
  const likeType = url.searchParams.get('likeType') || 'all'

  // 生成点赞的电视剧数据
  const likedDramas = Mock.mock({
    [`list|${pageSize * 3}`]: [
      {
        ...videoTemplate,
        // 点赞相关字段
        likeTime: '@date("yyyy-MM-dd")', // 点赞时间
        likeType: '@pick(["drama", "episode"])', // 点赞类型：电视剧点赞或单集点赞
        isLiked: true, // 确保都是已点赞状态

        // 如果是单集点赞，需要包含具体的集数信息
        likedEpisode: function () {
          if (this.likeType === 'episode') {
            return {
              'episodeId|101-150': 1,
              'episodeNumber|1-50': 1,
              episodeTitle: '第@integer(1, 50)集 @ctitle(3, 8)',
              likeTime: '@date("yyyy-MM-dd")',
              cover: () => getRandomImage(200, 150, 'episode')
            }
          }
          return null
        },

        // 点赞来源信息
        likeSource: '@pick(["drama_detail", "episode_play", "featured_list", "search_result"])', // 点赞来源
        deviceType: '@pick(["mobile", "desktop", "tablet"])', // 点赞设备

        // 电视剧当前状态
        currentUserProgress: '@integer(0, 30)', // 用户当前观看进度
        isStillFollowing: '@boolean', // 是否还在追剧
        hasNewUpdate: '@boolean', // 是否有新更新
        'newEpisodeCount|0-5': 1 // 新集数数量
      }
    ]
  }).list

  // 根据点赞类型筛选
  let filteredList = likedDramas
  if (likeType === 'drama') {
    filteredList = likedDramas.filter((item) => item.likeType === 'drama')
  } else if (likeType === 'episode') {
    filteredList = likedDramas.filter((item) => item.likeType === 'episode')
  }

  // 排序
  if (sort === 'drama_title') {
    filteredList.sort((a, b) => a.title.localeCompare(b.title))
  } else if (sort === 'update_time') {
    filteredList.sort((a, b) => new Date(b.releaseDate) - new Date(a.releaseDate))
  } else {
    filteredList.sort((a, b) => new Date(b.likeTime) - new Date(a.likeTime))
  }

  // 分页
  const total = filteredList.length
  const start = (page - 1) * pageSize
  const end = start + pageSize
  const list = filteredList.slice(start, end)

  return {
    code: 200,
    message: 'success',
    data: {
      list,
      pagination: {
        page,
        pageSize,
        total,
        totalPages: Math.ceil(total / pageSize)
      },
      statistics: {
        totalLiked: total,
        dramaLikedCount: filteredList.filter((item) => item.likeType === 'drama').length,
        episodeLikedCount: filteredList.filter((item) => item.likeType === 'episode').length,
        stillFollowingCount: list.filter((item) => item.isStillFollowing).length,
        hasUpdateCount: list.filter((item) => item.hasNewUpdate).length,
        recentLikedCount: list.filter((item) => {
          const likeTime = new Date(item.likeTime)
          const now = new Date()
          const diffDays = (now - likeTime) / (1000 * 60 * 60 * 24)
          return diffDays <= 7
        }).length
      }
    }
  }
})

// ==================== 浏览记录删除相关Mock API ====================

/**
 * 删除单条浏览记录 API
 * DELETE /api/user/browsing-history/:recordId
 */
Mock.mock(/\/api\/user\/browsing-history\/(\d+)$/, 'delete', (options) => {
  const recordId = options.url.match(/\/api\/user\/browsing-history\/(\d+)$/)[1]

  return {
    code: 200,
    message: '浏览记录删除成功',
    data: {
      recordId: parseInt(recordId),
      deletedAt: '@date("yyyy-MM-dd")'
    }
  }
})

/**
 * 批量删除浏览记录 API
 * DELETE /api/user/browsing-history/batch
 * Body: { recordIds: [1, 2, 3] }
 */
Mock.mock(/\/api\/user\/browsing-history\/batch$/, 'delete', (options) => {
  const body = JSON.parse(options.body)
  const { recordIds } = body

  // 模拟部分删除失败的情况
  const successIds = recordIds.filter(() => Math.random() > 0.1) // 90%成功率
  const failedIds = recordIds.filter((id) => !successIds.includes(id))

  return {
    code: 200,
    message: `成功删除 ${successIds.length} 条记录${failedIds.length > 0 ? `，${failedIds.length} 条删除失败` : ''}`,
    data: {
      successCount: successIds.length,
      failedCount: failedIds.length,
      successIds,
      failedIds,
      totalRequested: recordIds.length,
      deletedAt: '@date("yyyy-MM-dd")'
    }
  }
})

// ==================== 追剧删除相关Mock API ====================

/**
 * 删除单个追剧 API
 * DELETE /api/user/following/:dramaId
 */
Mock.mock(/\/api\/user\/following\/(\d+)$/, 'delete', (options) => {
  const dramaId = options.url.match(/\/api\/user\/following\/(\d+)$/)[1]

  return {
    code: 200,
    message: '取消追剧成功',
    data: {
      dramaId: parseInt(dramaId),
      isFollowing: false,
      unfollowTime: '@date("yyyy-MM-dd")',
      // 返回一些统计信息
      watchedEpisodes: '@integer(1, 20)',
      totalWatchTime: '@integer(1000, 50000)', // 总观看时间(分钟)
      followDuration: '@integer(1, 365)' // 追剧天数
    }
  }
})

/**
 * 批量删除追剧 API
 * DELETE /api/user/following/batch
 * Body: { dramaIds: [1, 2, 3] }
 */
Mock.mock(/\/api\/user\/following\/batch$/, 'delete', (options) => {
  console.log('Mock: 批量删除追剧 API 被调用', options.url, options.body)

  try {
    const body = JSON.parse(options.body)
    const { dramaIds } = body

    console.log('Mock: 解析到的 dramaIds:', dramaIds)

    if (!dramaIds || !Array.isArray(dramaIds) || dramaIds.length === 0) {
      return {
        code: 400,
        message: '电视剧ID数组不能为空',
        data: null
      }
    }

    // 确保所有ID都是数字类型
    const normalizedIds = dramaIds.map((id) => Number(id)).filter((id) => !isNaN(id) && id > 0)

    if (normalizedIds.length === 0) {
      return {
        code: 400,
        message: '没有有效的电视剧ID',
        data: null
      }
    }

    // 模拟部分删除失败的情况（95%成功率）
    const successIds = normalizedIds.filter(() => Math.random() > 0.05)
    const failedIds = normalizedIds.filter((id) => !successIds.includes(id))

    // 为成功删除的追剧生成统计信息
    const deletedDramas = successIds.map((id) => ({
      dramaId: id,
      dramaTitle: Mock.Random.ctitle(5, 15),
      watchedEpisodes: Mock.Random.integer(1, 30),
      totalWatchTime: Mock.Random.integer(500, 20000), // 观看时间(分钟)
      followDuration: Mock.Random.integer(1, 200) // 追剧天数
    }))

    console.log('Mock: 返回删除结果', { successCount: successIds.length, failedCount: failedIds.length })

    return {
      code: 200,
      message: `成功取消 ${successIds.length} 个追剧${failedIds.length > 0 ? `，${failedIds.length} 个取消失败` : ''}`,
      data: {
        successCount: successIds.length,
        failedCount: failedIds.length,
        successIds,
        failedIds,
        totalRequested: dramaIds.length,
        unfollowTime: new Date().toISOString().split('T')[0],
        deletedDramas, // 被删除的追剧详细信息
        summary: {
          totalWatchTime: deletedDramas.reduce((sum, drama) => sum + drama.totalWatchTime, 0),
          totalWatchedEpisodes: deletedDramas.reduce((sum, drama) => sum + drama.watchedEpisodes, 0),
          averageFollowDuration:
            Math.round(deletedDramas.reduce((sum, drama) => sum + drama.followDuration, 0) / deletedDramas.length) || 0
        }
      }
    }
  } catch (error) {
    console.error('Mock: 批量删除追剧解析失败:', error)
    return {
      code: 500,
      message: '服务器内部错误: ' + error.message,
      data: null
    }
  }
})

// ==================== 用户收藏相关Mock API ====================

/**
 * 获取用户收藏列表 API
 * GET /api/user/favorites?page=1&pageSize=10&sort=favorite_time&favoriteType=all
 */
Mock.mock(/\/api\/user\/favorites(\?.*)?$/, 'get', (options) => {
  const url = new URL('http://localhost' + options.url)
  const page = parseInt(url.searchParams.get('page')) || 1
  const pageSize = parseInt(url.searchParams.get('pageSize')) || 10
  const sort = url.searchParams.get('sort') || 'favorite_time'
  const favoriteType = url.searchParams.get('favoriteType') || 'all'

  // 生成收藏的电视剧和单集数据
  const favoritesList = Mock.mock({
    [`list|${pageSize * 3}`]: [
      {
        ...videoTemplate,
        // 收藏相关字段
        favoriteTime: '@date("yyyy-MM-dd")', // 收藏时间
        favoriteType: '@pick(["drama", "episode"])', // 收藏类型：电视剧收藏或单集收藏
        isFavorited: true, // 确保都是已收藏状态
        favoriteId: '@increment(10000)', // 收藏记录的唯一ID

        // 如果是单集收藏，需要包含具体的集数信息
        favoritedEpisode: function () {
          if (this.favoriteType === 'episode') {
            return {
              'episodeId|101-150': 1,
              'episodeNumber|1-50': 1,
              episodeTitle: '第@integer(1, 50)集 @ctitle(3, 8)',
              favoriteTime: '@date("yyyy-MM-dd")',
              cover: () => getRandomImage(200, 150, 'episode'),
              duration: '@pick(["42:30", "45:15", "48:20", "50:45", "38:10"])',
              'likeCount|500-9999': 1,
              'viewCount|1000-99999': 1
            }
          }
          return null
        },

        // 收藏来源信息
        favoriteSource: '@pick(["drama_detail", "episode_play", "featured_list", "search_result"])', // 收藏来源
        deviceType: '@pick(["mobile", "desktop", "tablet"])', // 收藏设备

        // 电视剧当前状态
        currentUserProgress: '@integer(0, 30)', // 用户当前观看进度
        isStillFollowing: '@boolean', // 是否还在追剧
        hasNewUpdate: '@boolean', // 是否有新更新
        'newEpisodeCount|0-5': 1, // 新集数数量

        // 收藏备注（用户可能添加的个人备注）
        favoriteNote: '@pick([null, "@csentence(5, 20)"])', // 收藏备注，50%概率为空

        // 收藏分类标签（用户自定义分类）
        favoriteCategory: '@pick(["待看", "正在看", "看完了", "经典收藏", "推荐给朋友"])', // 用户自定义分类

        // 收藏统计
        'favoriteViewCount|0-50': 1, // 收藏后的观看次数
        lastViewTime: '@date("yyyy-MM-dd")' // 最后一次查看收藏的时间
      }
    ]
  }).list

  // 根据收藏类型筛选
  let filteredList = favoritesList
  if (favoriteType === 'drama') {
    filteredList = favoritesList.filter((item) => item.favoriteType === 'drama')
  } else if (favoriteType === 'episode') {
    filteredList = favoritesList.filter((item) => item.favoriteType === 'episode')
  }

  // 排序
  if (sort === 'drama_title') {
    filteredList.sort((a, b) => a.title.localeCompare(b.title))
  } else if (sort === 'update_time') {
    filteredList.sort((a, b) => new Date(b.releaseDate) - new Date(a.releaseDate))
  } else {
    filteredList.sort((a, b) => new Date(b.favoriteTime) - new Date(a.favoriteTime))
  }

  // 分页
  const total = filteredList.length
  const start = (page - 1) * pageSize
  const end = start + pageSize
  const list = filteredList.slice(start, end)

  return {
    code: 200,
    message: 'success',
    data: {
      list,
      pagination: {
        page,
        pageSize,
        total,
        totalPages: Math.ceil(total / pageSize)
      },
      statistics: {
        totalFavorites: total,
        dramaFavoritesCount: filteredList.filter((item) => item.favoriteType === 'drama').length,
        episodeFavoritesCount: filteredList.filter((item) => item.favoriteType === 'episode').length,
        stillFollowingCount: list.filter((item) => item.isStillFollowing).length,
        hasUpdateCount: list.filter((item) => item.hasNewUpdate).length,
        recentFavoritesCount: list.filter((item) => {
          const favoriteTime = new Date(item.favoriteTime)
          const now = new Date()
          const diffDays = (now - favoriteTime) / (1000 * 60 * 60 * 24)
          return diffDays <= 7
        }).length,
        categoriesCount: {
          待看: list.filter((item) => item.favoriteCategory === '待看').length,
          正在看: list.filter((item) => item.favoriteCategory === '正在看').length,
          看完了: list.filter((item) => item.favoriteCategory === '看完了').length,
          经典收藏: list.filter((item) => item.favoriteCategory === '经典收藏').length,
          推荐给朋友: list.filter((item) => item.favoriteCategory === '推荐给朋友').length
        }
      }
    }
  }
})

/**
 * 删除单个收藏 API
 * DELETE /api/user/favorites/:type/:id
 */
Mock.mock(/\/api\/user\/favorites\/(drama|episode)\/(\d+)$/, 'delete', (options) => {
  const matches = options.url.match(/\/api\/user\/favorites\/(drama|episode)\/(\d+)$/)
  const type = matches[1] // 'drama' 或 'episode'
  const id = matches[2] // 对应的ID

  // 生成删除的收藏项目信息
  const deletedFavorite = Mock.mock({
    favoriteId: '@increment(10000)',
    type: type,
    id: parseInt(id),
    title: type === 'drama' ? '@ctitle(5, 15)' : '第@integer(1, 50)集 @ctitle(3, 8)',
    favoriteTime: '@date("yyyy-MM-dd")',
    favoriteCategory: '@pick(["待看", "正在看", "看完了", "经典收藏", "推荐给朋友"])',
    'favoriteViewCount|0-50': 1,
    'totalWatchTime|0-5000': 1 // 通过收藏观看的总时长(分钟)
  })

  return {
    code: 200,
    message: `${type === 'drama' ? '电视剧' : '单集'}收藏删除成功`,
    data: {
      deletedFavorite,
      unfavoriteTime: '@date("yyyy-MM-dd")'
    }
  }
})

/**
 * 批量删除收藏 API
 * DELETE /api/user/favorites/batch
 * Body: { favoriteItems: [{type: 'drama', id: 1}, {type: 'episode', id: 101}] }
 */
Mock.mock(/\/api\/user\/favorites\/batch$/, 'delete', (options) => {
  const body = JSON.parse(options.body)
  const { favoriteItems } = body

  // 模拟部分删除失败的情况
  const successItems = favoriteItems.filter(() => Math.random() > 0.05) // 95%成功率
  const failedItems = favoriteItems.filter((item) => !successItems.includes(item))

  // 为成功删除的收藏生成详细信息
  const deletedFavorites = successItems.map((item) => ({
    favoriteId: Mock.Random.increment(10000),
    type: item.type,
    id: parseInt(item.id),
    title:
      item.type === 'drama'
        ? Mock.Random.ctitle(5, 15)
        : `第${Mock.Random.integer(1, 50)}集 ${Mock.Random.ctitle(3, 8)}`,
    favoriteTime: Mock.Random.date('yyyy-MM-dd'),
    favoriteCategory: Mock.Random.pick(['待看', '正在看', '看完了', '经典收藏', '推荐给朋友']),
    favoriteViewCount: Mock.Random.integer(0, 50),
    totalWatchTime: Mock.Random.integer(0, 5000) // 通过收藏观看的总时长(分钟)
  }))

  // 按类型分组统计
  const dramaCount = deletedFavorites.filter((item) => item.type === 'drama').length
  const episodeCount = deletedFavorites.filter((item) => item.type === 'episode').length

  return {
    code: 200,
    message: `成功删除 ${successItems.length} 个收藏${failedItems.length > 0 ? `，${failedItems.length} 个删除失败` : ''}`,
    data: {
      successCount: successItems.length,
      failedCount: failedItems.length,
      successItems: successItems.map((item) => ({ type: item.type, id: item.id })),
      failedItems: failedItems.map((item) => ({ type: item.type, id: item.id, reason: '网络错误或数据不存在' })),
      totalRequested: favoriteItems.length,
      unfavoriteTime: '@date("yyyy-MM-dd")',
      deletedFavorites, // 被删除的收藏详细信息
      summary: {
        deletedDramaCount: dramaCount, // 删除的电视剧收藏数
        deletedEpisodeCount: episodeCount, // 删除的单集收藏数
        totalWatchTime: deletedFavorites.reduce((sum, fav) => sum + fav.totalWatchTime, 0), // 总观看时长
        totalViewCount: deletedFavorites.reduce((sum, fav) => sum + fav.favoriteViewCount, 0), // 总查看次数
        categoriesAffected: [...new Set(deletedFavorites.map((fav) => fav.favoriteCategory))], // 受影响的分类
        oldestFavorite: deletedFavorites.reduce(
          (oldest, fav) => (new Date(fav.favoriteTime) < new Date(oldest.favoriteTime) ? fav : oldest),
          deletedFavorites[0]
        ), // 最早的收藏
        newestFavorite: deletedFavorites.reduce(
          (newest, fav) => (new Date(fav.favoriteTime) > new Date(newest.favoriteTime) ? fav : newest),
          deletedFavorites[0]
        ) // 最新的收藏
      }
    }
  }
})

// ==================== 主页标签数据配置 ====================

// 主页标签配置
const homeTabsConfig = {
  recommend: {
    key: 'recommend',
    title: '推荐',
    hasCategories: true,
    categories: [
      { id: 1, key: 'featured', title: '精选', description: '编辑精心挑选的优质内容' },
      { id: 2, key: 'costume', title: '古装', description: '古色古香的历史传奇' },
      { id: 3, key: 'rebirth', title: '重生', description: '重生逆袭的精彩故事' },
      { id: 4, key: 'family', title: '家庭', description: '温馨感人的家庭故事' },
      { id: 5, key: 'romance', title: '恋爱', description: '甜蜜浪漫的爱情故事' },
      { id: 6, key: 'timetravel', title: '穿越', description: '穿越时空的奇幻冒险' }
    ]
  },
  ranking: {
    key: 'ranking',
    title: '排行榜',
    hasCategories: true,
    categories: [
      { id: 7, key: 'hot', title: '热播榜', description: '当前最热门的电视剧' },
      { id: 8, key: 'rising', title: '飙升榜', description: '人气急速上升的剧集' },
      { id: 9, key: 'new', title: '新剧榜', description: '最新上线的优质剧集' },
      { id: 10, key: 'trending', title: '热搜榜', description: '社交媒体热议的剧集' }
    ]
  },
  newDrama: {
    key: 'newDrama',
    title: '新剧',
    hasCategories: false,
    categories: []
  },
  classic: {
    key: 'classic',
    title: '经典好剧',
    hasCategories: false,
    categories: []
  }
}

// 根据标签和分类生成对应的电视剧数据
const generateDramasByTabAndCategory = (tabKey, categoryKey = null, count = 20) => {
  console.log('🎨 Mock: 生成电视剧数据', { tabKey, categoryKey, count })

  const baseTemplate = { ...videoTemplate }

  // 根据不同标签调整数据特征
  switch (tabKey) {
    case 'recommend':
      baseTemplate['rating|8.0-9.5'] = 1
      baseTemplate['likeCount|50000-999999'] = 1
      baseTemplate['viewCount|1000000-9999999'] = 1
      baseTemplate.isPopular = true

      if (categoryKey) {
        switch (categoryKey) {
          case 'featured':
            baseTemplate.tags = ['精选', '口碑', '必看']
            baseTemplate.featuredReason = '@pick(["编辑推荐", "用户好评", "口碑佳作"])'
            break
          case 'costume':
            baseTemplate.tags = ['古装', '历史', '宫廷', '武侠']
            break
          case 'rebirth':
            baseTemplate.tags = ['重生', '逆袭', '玄幻', '现代']
            break
          case 'family':
            baseTemplate.tags = ['家庭', '温情', '亲情', '生活']
            break
          case 'romance':
            baseTemplate.tags = ['恋爱', '浪漫', '甜宠', '都市']
            break
          case 'timetravel':
            baseTemplate.tags = ['穿越', '古代', '现代', '奇幻']
            break
        }
      }
      break

    case 'ranking':
      baseTemplate['rank|1-100'] = 1
      baseTemplate['rankChange|1-20'] = 1
      baseTemplate.rankDirection = '@pick(["up", "down", "same", "new"])'

      if (categoryKey) {
        switch (categoryKey) {
          case 'hot':
            baseTemplate['viewCount|5000000-99999999'] = 1
            baseTemplate['hotScore|90-100'] = 1
            break
          case 'rising':
            baseTemplate['growthRate|50-500'] = 1
            baseTemplate.isRising = true
            break
          case 'new':
            baseTemplate.isNew = true
            baseTemplate.releaseDate = '@date("yyyy-MM-dd", "now", "-30d")'
            break
          case 'trending':
            baseTemplate['searchVolume|100000-9999999'] = 1
            baseTemplate['socialMentions|10000-999999'] = 1
            break
        }
      }
      break

    case 'newDrama':
      console.log('🆕 Mock: 生成新剧数据')
      baseTemplate.isNew = true
      baseTemplate.releaseDate = '@date("yyyy-MM-dd", "now", "-60d")'
      baseTemplate['currentEpisode|1-10'] = 1
      baseTemplate.tags = ['新剧', '热门', '追剧']
      baseTemplate['rating|7.5-9.0'] = 1
      break

    case 'classic':
      console.log('🏆 Mock: 生成经典好剧数据')
      baseTemplate.isCompleted = true
      baseTemplate['rating|8.5-9.8'] = 1
      baseTemplate['ratingCount|50000-999999'] = 1
      baseTemplate.releaseDate = '@date("yyyy-MM-dd", "2010", "2020")'
      baseTemplate.tags = ['经典', '高分', '必看', '口碑']
      baseTemplate.classicReason = '@pick(["经典之作", "时代记忆", "口碑佳作", "重温经典"])'
      break

    default:
      console.warn('⚠️ Mock: 未知的标签类型:', tabKey)
      break
  }

  const result = Mock.mock({
    [`list|${count}`]: [baseTemplate]
  }).list

  console.log('✨ Mock: 生成电视剧数据完成', {
    tabKey,
    categoryKey,
    requestedCount: count,
    actualCount: result.length,
    sampleTitle: result[0]?.title || 'N/A'
  })

  return result
}

/**
 * 获取主页标签数据 API（扩展版）
 * GET /api/home/tabs/:tabKey
 * 根据标签返回对应的分类和数据，支持分类和分页参数
 */
Mock.mock(/\/api\/home\/tabs\/(recommend|ranking|newDrama|classic)$/, 'get', (options) => {
  const matches = options.url.match(/\/api\/home\/tabs\/(\w+)$/)
  if (!matches) {
    console.error('🚫 Mock: URL匹配失败:', options.url)
    return {
      code: 400,
      message: 'URL格式错误',
      data: null
    }
  }

  const tabKey = matches[1]
  console.log('🎯 Mock: 获取主页标签数据 API 被调用', { url: options.url, tabKey })

  // 解析URL参数
  let category = null
  let page = 1
  let pageSize = 20
  let withPagination = false

  try {
    if (options.url.includes('?')) {
      const url = new URL('http://localhost' + options.url)
      category = url.searchParams.get('category')
      page = parseInt(url.searchParams.get('page')) || 1
      pageSize = parseInt(url.searchParams.get('pageSize')) || 20
      withPagination = url.searchParams.get('withPagination') === 'true'
    }
  } catch (error) {
    console.warn('⚠️ Mock: URL参数解析失败，使用默认值:', error)
  }

  console.log('📝 Mock: 解析的参数', { tabKey, category, page, pageSize, withPagination })

  const tabConfig = homeTabsConfig[tabKey]
  if (!tabConfig) {
    console.error('🚫 Mock: 标签配置不存在:', tabKey)
    return {
      code: 404,
      message: '标签不存在',
      data: null
    }
  }

  console.log('📋 Mock: 找到标签配置:', tabConfig.title)

  // 如果指定了分类或启用分页模式，返回分页数据
  if (category || withPagination) {
    console.log('📄 Mock: 进入分页模式')

    // 验证分类参数
    if (tabConfig.hasCategories && category && !tabConfig.categories.find((cat) => cat.key === category)) {
      return {
        code: 400,
        message: '分类不存在',
        data: null
      }
    }

    // 生成当前页数据
    const dramas = generateDramasByTabAndCategory(tabKey, category, pageSize)

    // 模拟总数据量
    let totalCount
    if (category) {
      totalCount = Mock.Random.integer(200, 800)
    } else if (tabConfig.hasCategories) {
      totalCount = Mock.Random.integer(500, 2000)
    } else {
      totalCount = Mock.Random.integer(500, 2000)
    }

    const totalPages = Math.ceil(totalCount / pageSize)
    const hasMore = page < totalPages

    // 为排行榜数据添加排名信息
    if (tabKey === 'ranking') {
      dramas.forEach((drama, index) => {
        drama.rank = (page - 1) * pageSize + index + 1
        drama.pageRank = index + 1
      })
    }

    const paginationResult = {
      code: 200,
      message: 'success',
      data: {
        tab: {
          key: tabKey,
          title: tabConfig.title,
          hasCategories: tabConfig.hasCategories,
          categories: tabConfig.categories
        },
        currentCategory: category ? tabConfig.categories.find((cat) => cat.key === category) : null,
        list: dramas,
        pagination: {
          page,
          pageSize,
          total: totalCount,
          totalPages,
          hasMore,
          isFirstPage: page === 1,
          isLastPage: page === totalPages
        },
        mode: 'pagination',
        loadTime: new Date().toISOString(),
        metadata: {
          dataSource: `${tabKey}${category ? `_${category}` : ''}`,
          generatedAt: new Date().toISOString(),
          pageIdentifier: `${tabKey}_${category || 'default'}_page_${page}`,
          cacheKey: `home_${tabKey}_${category || 'default'}_${page}_${pageSize}`
        }
      }
    }

    console.log('✅ Mock: 返回分页数据', {
      tabKey,
      dramasCount: dramas.length,
      totalCount,
      mode: 'pagination'
    })

    return paginationResult
  }

  console.log('📊 Mock: 进入初始数据模式')

  // 返回初始分类数据
  let responseData = {
    tab: tabConfig,
    mode: 'initial',
    timestamp: new Date().toISOString()
  }

  if (tabConfig.hasCategories) {
    console.log('🏷️ Mock: 处理有分类的标签:', tabKey)
    // 有分类的标签（推荐、排行榜）
    responseData.categories = tabConfig.categories.map((category) => {
      const dramas = generateDramasByTabAndCategory(tabKey, category.key, 20)

      return {
        ...category,
        dramas,
        totalCount: Mock.Random.integer(100, 500),
        statistics: {
          newCount: dramas.filter((drama) => drama.isNew).length,
          popularCount: dramas.filter((drama) => drama.isPopular).length,
          completedCount: dramas.filter((drama) => drama.isCompleted).length,
          avgRating: (dramas.reduce((sum, drama) => sum + (drama.rating || 8.0), 0) / dramas.length).toFixed(1)
        }
      }
    })
    console.log('✅ Mock: 有分类标签数据生成完成', {
      categoriesCount: responseData.categories.length,
      totalDramas: responseData.categories.reduce((sum, cat) => sum + cat.dramas.length, 0)
    })
  } else {
    console.log('📺 Mock: 处理无分类的标签:', tabKey)
    // 无分类的标签（新剧、经典好剧）- 确保生成数据
    const dramas = generateDramasByTabAndCategory(tabKey, null, 20)
    console.log('🎬 Mock: 生成的剧集数量:', dramas.length)

    responseData.dramas = dramas
    responseData.totalCount = Mock.Random.integer(200, 1000)
    responseData.statistics = {
      totalShows: dramas.length,
      avgRating:
        dramas.length > 0
          ? (dramas.reduce((sum, drama) => sum + (drama.rating || 8.0), 0) / dramas.length).toFixed(1)
          : '8.5',
      completedCount: dramas.filter((drama) => drama.isCompleted).length,
      ongoingCount: dramas.filter((drama) => !drama.isCompleted).length
    }

    console.log('✅ Mock: 无分类标签数据生成完成:', {
      tabKey,
      dramasCount: responseData.dramas.length,
      totalCount: responseData.totalCount,
      statistics: responseData.statistics
    })
  }

  const finalResult = {
    code: 200,
    message: 'success',
    data: responseData
  }

  console.log('🚀 Mock: 最终返回结果检查:', {
    hasData: !!finalResult.data,
    hasTab: !!finalResult.data.tab,
    hasCategories: !!finalResult.data.categories,
    hasDramas: !!finalResult.data.dramas,
    dramasCount: finalResult.data.dramas?.length || 0,
    categoriesCount: finalResult.data.categories?.length || 0,
    mode: finalResult.data.mode
  })

  return finalResult
})

/**
 * 获取主页分页数据 API
 * GET /api/home/tabs/:tabKey/page?page=2&pageSize=20&category=featured
 * 支持分页加载更多数据
 */
Mock.mock(/\/api\/home\/tabs\/(recommend|ranking|newDrama|classic)\/page(\?.*)?$/, 'get', (options) => {
  const tabKey = options.url.match(/\/api\/home\/tabs\/(\w+)\/page/)[1]

  // 解析URL参数
  const url = new URL('http://localhost' + options.url)
  const page = parseInt(url.searchParams.get('page')) || 1
  const pageSize = parseInt(url.searchParams.get('pageSize')) || 20
  const category = url.searchParams.get('category') // 分类标识，对于新剧和经典好剧为空

  console.log('获取主页分页数据 API 被调用', { tabKey, page, pageSize, category })

  const tabConfig = homeTabsConfig[tabKey]
  if (!tabConfig) {
    return {
      code: 404,
      message: '标签不存在',
      data: null
    }
  }

  // 验证分类参数
  if (tabConfig.hasCategories && !category) {
    return {
      code: 400,
      message: '该标签需要指定分类参数',
      data: null
    }
  }

  if (tabConfig.hasCategories && !tabConfig.categories.find((cat) => cat.key === category)) {
    return {
      code: 400,
      message: '分类不存在',
      data: null
    }
  }

  // 生成当前页数据
  const dramas = generateDramasByTabAndCategory(tabKey, category, pageSize)

  // 模拟总数据量
  let totalCount
  if (tabConfig.hasCategories) {
    totalCount = Mock.Random.integer(200, 800) // 每个分类200-800条数据
  } else {
    totalCount = Mock.Random.integer(500, 2000) // 新剧和经典好剧500-2000条数据
  }

  const totalPages = Math.ceil(totalCount / pageSize)
  const hasMore = page < totalPages

  // 为排行榜数据添加排名信息
  if (tabKey === 'ranking') {
    dramas.forEach((drama, index) => {
      drama.rank = (page - 1) * pageSize + index + 1 // 全局排名
      drama.pageRank = index + 1 // 当前页排名
    })
  }

  return {
    code: 200,
    message: 'success',
    data: {
      list: dramas,
      pagination: {
        page,
        pageSize,
        total: totalCount,
        totalPages,
        hasMore,
        isFirstPage: page === 1,
        isLastPage: page === totalPages
      },
      tab: {
        key: tabKey,
        title: tabConfig.title,
        category: category ? tabConfig.categories.find((cat) => cat.key === category) : null // 已包含id字段
      },
      loadTime: new Date().toISOString(),
      // 额外的元数据
      metadata: {
        dataSource: `${tabKey}${category ? `_${category}` : ''}`,
        generatedAt: new Date().toISOString(),
        pageIdentifier: `${tabKey}_${category || 'default'}_page_${page}`,
        cacheKey: `home_${tabKey}_${category || 'default'}_${page}_${pageSize}`
      }
    }
  }
})

/**
 * 获取单集评论列表 API
 * GET /api/episodes/:episodeId/comments?page=1&pageSize=20&sort=newest&showSpoilers=false
 * 返回单集的评论列表，支持分页、排序和剧透过滤
 */
Mock.mock(/\/api\/episodes\/(\d+)\/comments(\?.*)?$/, 'get', (options) => {
  const episodeId = options.url.match(/\/api\/episodes\/(\d+)\/comments/)[1]

  // 解析URL参数
  const url = new URL('http://localhost' + options.url)
  const page = parseInt(url.searchParams.get('page')) || 1
  const pageSize = parseInt(url.searchParams.get('pageSize')) || 20
  const sort = url.searchParams.get('sort') || 'newest'
  const showSpoilers = url.searchParams.get('showSpoilers') === 'true'

  console.log('获取单集评论列表 API 被调用', { episodeId, page, pageSize, sort, showSpoilers })

  // 生成单集评论数据
  const allComments = Mock.mock({
    [`list|${pageSize * 10}`]: [
      {
        'id|+1': 10000, // 评论ID
        user: '@cname', // 评论用户名
        avatar: () => getRandomImage(50, 50, 'avatar'), // 用户头像
        content: '@cparagraph(1, 3)', // 评论内容，1-3段
        timestamp: '@date("yyyy-MM-dd HH:mm:ss")', // 评论时间
        'likeCount|0-999': 1, // 点赞数
        isLiked: '@boolean', // 当前用户是否点赞
        'replyCount|0-50': 1, // 回复数量
        isSpoiler: '@boolean(0.2)', // 是否包含剧透，20%概率为true
        'rating|0-10': 0, // 评分，0-10分，0表示未评分
        isAuthor: '@boolean(0.05)', // 是否为创作者回复，5%概率
        userLevel: '@integer(1, 6)', // 用户等级
        userTitle: '@pick(["初级追剧迷", "资深追剧迷", "追剧达人", "追剧专家", "追剧王者"])', // 用户头衔

        // 可能包含的图片
        images: function () {
          // 30%概率有图片
          if (Mock.Random.boolean(0.3)) {
            const imageCount = Mock.Random.integer(1, 3)
            const images = []
            for (let i = 0; i < imageCount; i++) {
              images.push(getRandomImage(300, 200, 'comment'))
            }
            return images
          }
          return []
        },

        // 回复列表，0-3条回复预览
        'replies|0-3': [
          {
            'id|+1': 50000, // 回复ID
            user: '@cname',
            avatar: () => getRandomImage(50, 50, 'avatar'),
            content: '@csentence(10, 50)',
            timestamp: '@date("yyyy-MM-dd HH:mm:ss")',
            'likeCount|0-99': 1,
            isLiked: '@boolean',
            isSpoiler: '@boolean(0.1)', // 回复中的剧透概率较小
            userLevel: '@integer(1, 6)',
            userTitle: '@pick(["初级追剧迷", "资深追剧迷", "追剧达人", "追剧专家", "追剧王者"])'
          }
        ],

        // 评论标签
        tags: function () {
          const possibleTags = ['精彩', '搞笑', '感人', '高能', '惊喜', '神展开', '烂尾', '吐槽']
          const tagCount = Mock.Random.integer(0, 3)
          if (tagCount === 0) return []

          const selectedTags = []
          for (let i = 0; i < tagCount; i++) {
            const tag = Mock.Random.pick(possibleTags)
            if (!selectedTags.includes(tag)) {
              selectedTags.push(tag)
            }
          }
          return selectedTags
        }
      }
    ]
  }).list

  // 过滤剧透评论（如果不显示剧透）
  let filteredComments = allComments
  if (!showSpoilers) {
    filteredComments = allComments.filter((comment) => !comment.isSpoiler)
  }

  // 排序
  if (sort === 'hottest') {
    filteredComments.sort((a, b) => b.likeCount - a.likeCount)
  } else {
    // 默认按最新排序
    filteredComments.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp))
  }

  // 分页
  const total = filteredComments.length
  const start = (page - 1) * pageSize
  const end = start + pageSize
  const list = filteredComments.slice(start, end)

  return {
    code: 200,
    message: 'success',
    data: {
      episodeId: parseInt(episodeId),
      comments: list,
      pagination: {
        page,
        pageSize,
        total,
        totalPages: Math.ceil(total / pageSize),
        hasMore: end < total
      },
      filters: {
        sort,
        showSpoilers,
        availableSorts: [
          { key: 'newest', label: '最新' },
          { key: 'hottest', label: '最热' }
        ]
      },
      statistics: {
        totalComments: total,
        spoilerCount: allComments.filter((comment) => comment.isSpoiler).length,
        ratingAvg:
          allComments.filter((comment) => comment.rating > 0).reduce((sum, comment) => sum + comment.rating, 0) /
            allComments.filter((comment) => comment.rating > 0).length || 0,
        ratingCount: allComments.filter((comment) => comment.rating > 0).length,
        withImagesCount: allComments.filter((comment) => comment.images.length > 0).length,
        mostLikedComment: [...allComments].sort((a, b) => b.likeCount - a.likeCount)[0] || null
      }
    }
  }
})

/**
 * 评论点赞/取消点赞 API
 * POST /api/comments/:commentId/like
 * Body: { action: 'like' | 'unlike' }
 */
Mock.mock(/\/api\/comments\/(\d+)\/like$/, 'post', (options) => {
  const commentId = options.url.match(/\/api\/comments\/(\d+)\/like$/)[1]
  const body = JSON.parse(options.body)
  const { action } = body // 'like' 表示点赞，'unlike' 表示取消点赞

  console.log('Mock: 评论点赞/取消点赞 API 被调用', { commentId, action })

  return {
    code: 200,
    message: action === 'like' ? '评论点赞成功' : '取消评论点赞成功',
    data: {
      commentId: parseInt(commentId),
      isLiked: action === 'like', // 当前点赞状态
      likeCount:
        action === 'like'
          ? Mock.Random.integer(1, 1000) // 点赞后的数量（随机值）
          : Mock.Random.integer(0, 999), // 取消点赞后的数量（随机值）
      updateTime: new Date().toISOString()
    }
  }
})
